<template>
  <view :class="theme">
    <view class="fixed"
      style="top: 0; left: 0; right: 0; bottom: 0; bottom: var(--window-bottom); top: var(--window-top); left: var(--window-left); right: var(--window-right);">
      <u-image width="100%" height="100%" src="/static/img/bg-task.png" />
    </view>

    <view class="f1" style="z-index: 1;">
      <view style="padding: 50px 80rpx;">
        <text class="color-2 fw-600 fs-30">行星等级：{{ planet.name || "Lv0" }}</text>
        <text class="mt-14 color-7 fs-22">
          <text>距离下一次升级还需</text>
          <text class="color-8">{{ planet.left_profit || 0 }}</text>
          <text>能源</text>
        </text>
        <view class="mt-30 fd-row color-2 fs-22">
          <text>{{ planet.name || "Lv0" }}</text>
          <view class="f1 height-30 ml-12 mr-12 br-18" style="background-color: #3c4f87;">
            <view class="height-100percent br-18"
              :style="{ transition: `all 0.3s linear`, width: `${(planet.left_radio * 100) || 0}%`, backgroundImage: `linear-gradient(90deg, #f6a7a3, #eb5080)` }" />
          </view>
          <text>{{ planet.last_name || "Lv1" }}</text>
        </view>
      </view>
      <view class="ml-20 mr-20 relative">
        <u-image width="100%" height="600" src="/static/img/img-planet.png" />
        <u-image @click="collect(index)" v-for="(core, index) in cores" :key="index" class="absolute wobble" :style="core"
          width="116" height="116" src="/static/img/img-core.png" />
      </view>

      <view class="mt-120 as-center" hover-class="tap-hover">
        <u-image @click="beforeCollectAll" width="330" height="140" src="/static/img/btn-collect.png" />
      </view>
      <view class="f1 fd-row jc-sb ai-center color-2 fs-30 m-30">
        <view @click="showPopup.decompose = true" hover-class="tap-hover" class="ai-center">
          <u-image width="80" height="80" src="/static/img/icon-coin.png" />
          <text class="mt-24">分解星核</text>
        </view>

        <view @click="uniNavigator({ url: '/pages/client/main/tasks' })" hover-class="tap-hover" class="ai-center">
          <u-image width="80" height="80" src="/static/img/icon-myTask.png" />
          <text class="mt-24">我的星球</text>
        </view>

        <view @click="uniNavigator({ url: '/pages/client/main/ranking?rankingType=1' })" hover-class="tap-hover"
          class="ai-center">
          <u-image width="80" height="80" src="/static/img/ranking/icon-ranking_1.png" />
          <text class="mt-24">直推榜</text>
        </view>
        <view @click="uniNavigator({ url: '/pages/client/main/ranking?rankingType=2' })" hover-class="tap-hover"
          class="ai-center">
          <u-image width="80" height="80" src="/static/img/ranking/icon-ranking_2.png" />
          <text class="mt-24">能源榜</text>
        </view>
      </view>
    </view>

    <u-popup v-model="showPopup.decompose" @input="changePopup($event, 'decompose')" mode="center" closeable
      :mask-close-able="false" close-icon-color="#8c9ff7">
      <view class="relative">
        <u-image width="636" height="690" src="/static/img/bg-decompose_popup.png" />
        <view class="absolute jc-sb" style="top: 362rpx; right: 70rpx; bottom: 70rpx; left: 70rpx;">
          <input v-model="decomposeNumber" class="height-90 bg-11 br-8 pl-30 pr-30 fs-30" type="number"
            placeholder="请输入分解数量" placeholder-class="color-16">
          <button @click="decompose" hover-class="tap-hover" class="bg-12 br-46 color-2 fs-30 fw-600 m-0 lh-3">分解</button>
        </view>
      </view>
    </u-popup>

    <u-popup v-model="showPopup.password" @input="changePopup($event, 'password')" mode="center" closeable
      :mask-close-able="false" close-icon-color="#333">
      <view class="bg-2 oh br-20" style="width: 90vw;">
        <view class="mt-30 ai-center">
          <text class="mt-16 mb-30 color-6 fs-32 fw-700">请输入支付密码</text>
          <u-message-input @change="inputPayPassword" @finish="decompose" focus width="80" :maxlength="6" space="5"
            dot-fill />
        </view>
        <view @click="uniNavigator({ url: `/pages/client/main/setPayPassword` })" hover-class="tap-hover"
          class="mt-10 mb-30 p-20 as-center ml-12 color-15" style="text-decoration: underline;">
          忘记支付密码？
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script lang="ts" setup>

import { useMapState } from "@/common/libs/store";
import { debounce, uniNavigator } from "@/common/libs/utils";
import { onLoad, onPullDownRefresh, onReady, onTabItemTap } from "@dcloudio/uni-app";
import { ref, reactive } from "vue";

const { theme } = useMapState(["theme"]);

const corePositions = [
  { left: `120rpx`, top: `46rpx` },
  { right: `36rpx`, top: `90rpx` },
  { bottom: `-30rpx`, right: `240rpx` },
  { left: `40rpx`, bottom: `190rpx` },
  { right: `260rpx`, top: 0 },
  { right: `60rpx`, bottom: `46rpx` },
  { bottom: 0, left: `120rpx` },
  { right: `20rpx`, top: `280rpx` },
];
const cores = ref<any[]>([]);
const showPopup = reactive({
  decompose: false,
  password: false,
});
const decomposeNumber = ref("");
const payPassword = ref("");
const planet = ref<any>({});

onPullDownRefresh(() => {
  getPlanet();
  setTimeout(() => {
    uni.stopPullDownRefresh();
  }, 360);
});

onLoad(() => {
  uni.setTabBarStyle({
    backgroundColor: "#24293f",
    borderStyle: "#24293f",
  });
  getPlanet();
});

onTabItemTap((e) => {
  uni.setTabBarStyle({
    backgroundColor: "#24293f",
    borderStyle: "black",
  });
});
const refs = {
  adRewardedVideo: {} as UniApp.RewardedVideoAdContext,
  adInterstitial: {} as UniApp.InterstitialAdContext
};
let _isLoaded = false;
onReady(() => {
  refs.adRewardedVideo = uni.createRewardedVideoAd({
    adpid: '1759662325',
  });
  refs.adInterstitial = uni.createInterstitialAd({
    adpid: '1035559566'
  });

  refs.adRewardedVideo.onLoad((e) => {
    console.log(e);
  });
  refs.adRewardedVideo.onError((e) => {
    if (e && e.errMsg) {
      _isLoaded = false;
    }
  });
  refs.adRewardedVideo.onClose((e) => {
    _isLoaded = false;
    if (e && e.isEnded) {
      collectAll();
      return;
    }
    uni.showModal({ title: "温馨提示", content: "观看完成广告即可领取收益", showCancel: false });
  });
});

const collectAll = () => {
  uni.showToast({ icon: "loading", mask: true, duration: 6000 });
  uni.request({
    url: "/receivePackProfit",
    success({ msg: content }: any) {
      getPlanet();
      cores.value = [];
      uni.hideToast();
      uni.showModal({ title: "温馨提示", content, showCancel: false });
    }
  });
}

const beforeCollectAll = debounce(() => {
  // #ifdef APP-PLUS
  if (!_isLoaded) {
    _isLoaded = true;
    refs.adRewardedVideo.show().catch(res => collectAll());
    refs.adInterstitial.show();
  }
  // #endif

  // #ifndef APP-PLUS
  uni.showToast({ title: "请在App端操作", icon: "none" });
  // #endif
});

const collect = debounce((index: number) => {
  cores.value.splice(index, 1);
  !cores.value.length && beforeCollectAll();
});

const changePopup = (e: boolean, popupKey: keyof typeof showPopup) => {
  showPopup[popupKey] = e;
}

const inputPayPassword = (val: string) => {
  payPassword.value = val;
}

const getPlanet = () => {
  uni.request({
    url: "/initMask",
    success({ data }: any) {
      planet.value = data;
      const profit = data.today_profit * 100 / 8;
      cores.value = corePositions.slice(0, profit >= 8 ? 8 : ~~profit);
    }
  });
}

const decompose = () => {
  if (showPopup.password) {
    showPopup.password = false;
    uni.request({
      url: "/packJoin",
      data: { coin: decomposeNumber.value, pay_pass: payPassword.value },
      success({ msg: title }: any) {
        getPlanet();
        uni.showToast({ title });
        showPopup.decompose = false;
      }
    });
    return;
  }
  if (!decomposeNumber.value) {
    uni.showToast({ title: "请输入分解数量", icon: "none" });
    return;
  }
  showPopup.password = true;
}

</script>

<style>
page {
  height: 100%;
  background-color: #24293F;
}
</style>
<style lang="scss" scoped>
// scss
.dark,
.light {
  height: 100%;
}

@keyframes wobble {
  from {
    transform: translateY(0);
  }

  50% {
    transform: translateY(6px);
  }

  to {
    transform: translateY(0);
  }
}

.wobble {
  animation: wobble 2s ease-in-out infinite;
}
</style>